<template>
  <!-- 新增活动 -->
  <el-dialog
    v-model="visible"
    :title="form.composeId ? '修改组合捆绑活动' : '新增组合捆绑活动'"
    class="addGroupBuy"
    width="1000px"
    center
    top="10vh"
    :close-on-click-modal="false"
    @close="close"
  >
    <!-- 新增用户 -->
    <div class="addGroupBuyBox">
      <el-form
        ref="ruleFormRef"
        class="formBox"
        :model="form"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="活动名称" prop="composeName">
          <el-input
            v-model="form.composeName"
            maxlength="15"
            placeholder="请输入活动名称"
            oninput="value=value.replace(/\s+/g, '')"
          />
        </el-form-item>
        <el-form-item class="timeDataBox" label="活动时间" prop="startTime">
          <div class="dateBox">
            <el-form-item>
              <el-date-picker
                v-model="formExtra.dateInfo"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="changeDate"
              />
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item
          class="radio-group"
          label="促销类型"
          prop="composeType"
        >
          <div class="item">
            <el-radio
              v-model="form.composeType"
              :label="1"
            >直接定价</el-radio>
            <el-input-number
              v-model="formExtra.promote1"
              :controls="false"
              :max="10000000"
              :min="0.01"
              :precision="2"
            />&emsp;元
          </div>
          <div class="item">
            <el-radio
              v-model="form.composeType"
              :label="2"
            >固定减价</el-radio>
            <el-input-number
              v-model="formExtra.promote2"
              :controls="false"
              :max="10000000"
              :min="0.01"
              :precision="2"
            />&emsp;元
          </div>
          <div class="item">
            <el-radio v-model="form.composeType" :label="3">折扣</el-radio>
            <el-input-number
              v-model="formExtra.promote3"
              :precision="1"
              :min="1"
              :max="9.9"
              :step="0.1"
            />&emsp;折
          </div>
        </el-form-item>
        <el-form-item class="applyType" label="活动商品" prop="composeProducts">
          <span
            class="selectBtn"
            @click="chooseProduct"
          >请选择<i
            v-if="form.composeProducts.length !== 0"
            class="selectNum"
          >{{ form.composeProducts.length }}</i></span>
          <div class="selecTable">
            <el-table
              :data="formExtra.selectTableData"
              border
              :header-cell-style="{
                background: '#EEF3FF',
                color: '#333333'
              }"
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column
                prop="productId"
                label="商品id"
                show-overflow-tooltip
              />
              <el-table-column label="商品主图" width="150" align="center">
                <template #default="scope">
                  <img
                    height="80"
                    width="80"
                    :src="scope.row.productImage"
                    alt
                    srcset
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="productName"
                label="商品名称"
                width="220"
              />
              <el-table-column
                prop="section"
                label="售价区间"
                show-overflow-tooltip
              />
              <el-table-column
                prop="stockNumber"
                label="库存"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column label="操作" show-overflow-tooltip>
                <template #default="scope">
                  <div class="btnList">
                    <el-popconfirm
                      title="确定删除此活动？"
                      @confirm="delProduct(scope.row)"
                    >
                      <template #reference>
                        <el-button
                          class="delCls"
                          link
                          type="danger"
                        >删除</el-button>
                      </template>
                    </el-popconfirm>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button
        type="primary"
        @click="composeSubmit"
      >保 存</el-button>
      <el-button type="danger" @click="goToList">取 消</el-button>
    </template>
    <!-- 选择商品 -->
    <el-dialog
      v-model="productVisible"
      title="选择商品"
      width="55%"
      top="50px"
      class="group-dialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
    >
      <div class="formSearch">
        <el-form :inline="true" :model="productQuery">
          <el-form-item label="商品名称">
            <el-input
              v-model="productQuery.search"
              maxlength="20"
              placeholder="请输入商品名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getProList">查询</el-button>
            <el-button type="primary" @click="clear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          ref="multipleTableRef"
          :data="groupData"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          row-key="productId"
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
          />
          <el-table-column
            prop="productId"
            label="商品id"
            show-overflow-tooltip
          />
          <el-table-column label="商品主图" width="150" align="center">
            <template #default="scope">
              <img
                height="80"
                width="80"
                :src="scope.row.productImage"
                alt
                srcset
              />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" width="220" />
          <el-table-column
            prop="section"
            label="售价区间"
            show-overflow-tooltip
          />
          <el-table-column
            prop="stockNumber"
            label="库存"
            width="120"
            show-overflow-tooltip
          />
        </el-table>
        <div class="fenye">
          <el-pagination
            :current-page="productQuery.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="productQuery.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="saveIdList">确 定</el-button>
        <el-button @click="closeSelect">取 消</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { defineComponent, reactive, ref } from 'vue'

import {
  composeAdd,
  composeUpate,
  getComposeDetail,
  getComposeSelectProduct,
} from '@/api/marketing'

defineComponent({
  name: 'ComposeForm'
})

const emit = defineEmits(['reset']);

defineExpose({
  open, close
})

const productVisible = ref(false)

function initForm (data) {
  return {
    composeId: data && data.composeId || null,
    promote: data && data.promote || '',
    composeProducts: data && data.composeProducts || [], // 商品明细数据
    composeName: data && data.composeName || '', // 活动名称
    composeType: data && data.composeType || 1,
    startTime: data && data.startTime || '', // 活动开始时间
    endTime: data && data.endTime || '', // 活动结束时间
  }
}

const visible = ref(false)
const ruleFormRef = ref()
const form = ref(initForm())
const productQuery = ref({
  search: '',
  page: 1,
  pageSize: 10
})
const total = ref(0)
const groupData = ref([])
const multipleTableRef = ref()
const multipleSelection = ref([])
const formExtra = reactive({
  promote1: null,
  promote2: null,
  promote3: null,
  dateInfo: [],
  selectTableData: []
})
const checkTime = (rule, value, callback) => {
  if (formExtra.dateInfo[0] && formExtra.dateInfo[1]) {
    callback()
  } else {
    return callback(new Error('请选择活动时间'))
  }
}
const checkCompose = (rule, value, callback) => {
  if (value === 1 && !formExtra.promote1) {
    return callback(new Error('请输入直接定价价格'))
  } else if (value === 2 && !formExtra.promote2) {
    return callback(new Error('请输入固定减价价格'))
  } else if (value === 3 && !formExtra.promote3) {
    return callback(new Error('请输入折扣'))
  } else {
    callback()
  }
}
const checkProducts = (rule, value, callback) => {
  if (!value?.length || value.length < 2) {
    return callback(new Error('请选择至少两件活动商品'))
  } else {
    callback()
  }
}
const rules = {
  composeName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
  ],
  startTime: [
    { required: true, validator: checkTime, trigger: 'change' }
  ],
  composeType: [
    { required: true, validator: checkCompose, trigger: 'change' }
  ],
  composeProducts: [
    { required: true, validator: checkProducts, trigger: 'change' }
  ]
}

function vildateForm (str) {
  if (str) {
    ruleFormRef.value.validateField(str)
  }
}

function open (id) {
  form.value.composeId = id
  if (id) {
    getComposeInfo()
  }
  visible.value = true
}
function close () {
  visible.value = false
  form.value = initForm()
  productQuery.value.page = 1
  formExtra.dateInfo = []
  formExtra.promote1 = null
  formExtra.promote2 = null
  formExtra.promote3 = null
  formExtra.selectTableData = []
  multipleTableRef.value?.clearSelection()
  ruleFormRef.value?.resetFields()
}

function changeDate (e) {
  var startTime = Date.parse(e[1])
  var timestamp = Date.parse(new Date())
  if (startTime < timestamp) {
    formExtra.dateInfo = []
    ElMessage.warning('活动结束时间不能小于当前时间')
  }
}

function getProList () {
  getComposeSelectProduct(
    productQuery.value
  ).then((res) => {
    if (res.code === '') {
      groupData.value = res.data.list
      total.value = res.data.total
      for (let i = 0; i < groupData.value.length; i++) {
        for (let j = 0; j < formExtra.selectTableData.length; j++) {
          if (
            groupData.value[i].productId ===
            formExtra.selectTableData[j].productId
          ) {
            multipleTableRef.value.toggleRowSelection(groupData.value[i])
          }
        }
      }
    }
  })
}

function clear () {
  productQuery.value.search = ''
  getProList()
}

function handleCurrentChange (val) {
  productQuery.value.page = val
  getProList()
}

function handleSizeChange (val) {
  productQuery.value.pageSize = val
  getProList()
}

// 选择商品
function chooseProduct (type) {
  getProList()
  productVisible.value = true
}
// 选中商品
function handleSelectionChange (val) {
  multipleSelection.value = val
}
// 保存选择商品ID
function saveIdList () {
  const idList = []
  if (multipleSelection.value.length > 5) {
    ElMessage.warning('组合捆绑最多5个一组')
    return false
  }
  formExtra.selectTableData = multipleSelection.value
  multipleSelection.value.forEach((i) => {
    idList.push({
      composeId: form.value.composeId,
      productId: i.productId,
    })
  })
  form.value.composeProducts = idList
  multipleTableRef.value.clearSelection()
  productVisible.value = false
  vildateForm('composeProducts')
}
// 取消选择
function closeSelect () {
  productVisible.value = false
}
// 跳转秒杀列表
function goToList () {
  emit('reset')
}
function getComposeInfo () {
  getComposeDetail({
    composeId: form.value.composeId
  }).then(res => {
    // console.log(res,'res')
    // const dataList = []
    // res.data.composeProducts.forEach(item=>{
    //   dataList.push({
    //     composeId: res.data.composeId,
    //     productId: item.productId
    //   })
    // })
    // console.log(dataList,'dataList')
    // form.value.composeProducts = []
    // form.value.composeProducts = dataList
    form.value.composeName = res.data.composeName
    form.value.startTime = res.data.startTime
    form.value.endTime = res.data.endTime
    form.value.composeType = res.data.composeType
    switch (form.value.composeType) {
    case 1:
      formExtra.promote1 = res.data.promote
      break
    case 2:
      formExtra.promote2 = res.data.promote
      break
    case 3:
      formExtra.promote3 = res.data.promote
      break
    }
    formExtra.selectTableData = res.data.composeProducts.map((item) => {
      item.productImage = item.image
      item.section = item.sectionPrice
      return item
    })
    formExtra.selectTableData.forEach((i) => {
      form.value.composeProducts.push({
        productId: i.productId,
        composeId: form.value.composeId,
      })
    })
    formExtra.dateInfo = [form.value.startTime, form.value.endTime]
  })
}
// 删除产品
function delProduct (row) {
  var curIndex = 0
  form.value.composeProducts.forEach((item, index) => {
    if (item.productId === row.productId) {
      curIndex = index
    }
  })
  form.value.composeProducts.splice(curIndex, 1)
  formExtra.selectTableData.splice(curIndex, 1)
}

function composeSubmit () {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      switch (form.value.composeType) {
      case 1:
        form.value.promote = formExtra.promote1
        break
      case 2:
        form.value.promote = formExtra.promote2
        break
      case 3:
        form.value.promote = formExtra.promote3
        break
      }
      form.value.startTime = formExtra.dateInfo[0]
      form.value.endTime = formExtra.dateInfo[1]
      if (form.value.composeId) {
        composeUpate(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('修改成功')
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      } else {
        composeAdd(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('提交成功')
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      }
    } else {
      return false
    }
  })
}

</script>

<style lang="scss" scoped>
.addGroupBuy {
  background: #ffffff;
  .dialog-footer {
    display: flex;
    justify-content: center;
  }
  .formBox {
    .radio-group {
      .item {
        width: 100%;
        margin: 0 0 10px 0;
        :deep(.el-radio__label) {
          min-width: 70px;
        }
      }
    }
    .applyType {
      .selectBtn {
        width: 100px;
        height: 30px;
        line-height: 30px;
        background: #66b1ff;
        color: #ffffff;
        text-align: center;
        display: inline-block;
        font-size: 14px;
        margin-right: 30px;
        margin-bottom: 10px;
        border-radius: 4px;
        cursor: pointer;
        position: relative;
        i {
          position: absolute;
          right: -10px;
          top: -10px;
          width: 25px;
          height: 25px;
          line-height: 25px;
          background: #ffffff;
          border-radius: 50%;
          border: 1px solid #66b1ff;
          text-align: center;
          color: #3A68F2;
          font-style: normal;
          font-size: 12px;
        }
      }
    }
  }
  .dateBox {
    display: flex;
    align-items: center;
    .description {
      width: 59px;
      text-align: center;
      display: block;
      font-size: 14px;
      color: #999999;
    }
  }
}
</style>